// Level.cpp //
#include "level.h"
//creates a level and controls enemy spawns

Level Level::LevelOne; // could create more levels

Level::Level() //constructor
{
	timeElapsed = 0.0f;
	objectIndex = 0;
}

void Level::BuildLevel() //creates level
{
	Reset();
	
	ifstream file;
	//file holds spawn locations and times of all enemies
    file.open("resources/level.txt"); 

    string type = "";
    int positionX = 0;
	float time = 0.0f;
	
	float finalTime = 0.0f;

	getline(file, type);

	while(!file.eof())
    {
		file >> type;
		file >> positionX;
		file >> time;
		
		AddObject(type, positionX, time);

		finalTime = time; // used to spawn boss
	}

    file.close();
    
    finalTime += 15.0f; //see, it is used to spawn the boss
	
	AddObject("Boss", ScreenWidth / 2, finalTime);
}

//puts enemies on the list
void Level::AddObject(string type, float positionX, float spawnTime)
{
	LevelObject object;
	object.type = type;
	object.positionX = positionX;
	object.time = spawnTime;
	
	LevelObjects.push_back(object);
}

//actually spawns the enemies
void Level::SpawnObject(LevelObject object)
{
	if(object.type == "Boss")
	{
		Boss::SpawnBoss();
	}
	else
	{
		Enemy* enemy;
		int rPrime = rand() % 34;
		int newPrime = Primes[rPrime];
	    if(object.type == "StraightShooter")
		    enemy = new StraightShooter("StraightShooter");
		else if(object.type == "TargetShooter")
		    enemy = new TargetShooter("TargetShooter");
		else if(object.type == "Kamikaze")
		    enemy = new Kamikaze("Kamikaze");
		enemy->numValue = newPrime;
		enemy->position = Vector(object.positionX, -enemy->sprite->origin.Y);
	}
}

//reset level
void Level::Reset()
{
	timeElapsed = 0.0f;
	objectIndex = 0;
	
	LevelObjects.clear();
}

// spawn opbjects based on time
void Level::Update(float deltaTime)
{
	timeElapsed += deltaTime;
	
	for(int i = objectIndex; i < LevelObjects.size(); ++i)
	{
		if(LevelObjects[i].time > timeElapsed)
		    break;
		    
		SpawnObject(LevelObjects[i]);
		objectIndex++;
	}
}

